<!doctype html>

<html>
<head>
  <link rel="shortcut icon" href="static/images/favicon.ico" type="image/x-icon">
  <title>pubsub.js (Closure Library API Documentation - JavaScript)</title>
  <link rel="stylesheet" href="static/css/base.css">
  <link rel="stylesheet" href="static/css/doc.css">
  <link rel="stylesheet" href="static/css/sidetree.css">
  <link rel="stylesheet" href="static/css/prettify.css">

  <script>
     var _staticFilePath = "static/";
     var _typeTreeName = "goog";
     var _fileTreeName = "Source";
  </script>

  <script src="static/js/doc.js">
  </script>


  <meta charset="utf8">
</head>

<body onload="grokdoc.onLoad();">

<div id="header">
  <div class="g-section g-tpl-50-50 g-split">
    <div class="g-unit g-first">
      <a id="logo" href="index.html">Closure Library API Documentation</a>
    </div>

    <div class="g-unit">
      <div class="g-c">
        <strong>Go to class or file:</strong>
        <input type="text" id="ac">
      </div>
    </div>
  </div>
</div>

<div class="clear"></div>

<h2><a href="closure_goog_pubsub_pubsub.js.html">pubsub.js</a></h2>

<pre class="prettyprint lang-js">
<a name="line1"></a>// Copyright 2007 The Closure Library Authors. All Rights Reserved.
<a name="line2"></a>//
<a name="line3"></a>// Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);
<a name="line4"></a>// you may not use this file except in compliance with the License.
<a name="line5"></a>// You may obtain a copy of the License at
<a name="line6"></a>//
<a name="line7"></a>//      http://www.apache.org/licenses/LICENSE-2.0
<a name="line8"></a>//
<a name="line9"></a>// Unless required by applicable law or agreed to in writing, software
<a name="line10"></a>// distributed under the License is distributed on an &quot;AS-IS&quot; BASIS,
<a name="line11"></a>// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<a name="line12"></a>// See the License for the specific language governing permissions and
<a name="line13"></a>// limitations under the License.
<a name="line14"></a>
<a name="line15"></a>/**
<a name="line16"></a> * @fileoverview  Topic-based publish/subscribe channel implementation.
<a name="line17"></a> *
<a name="line18"></a> */
<a name="line19"></a>
<a name="line20"></a>goog.provide(&#39;goog.pubsub.PubSub&#39;);
<a name="line21"></a>
<a name="line22"></a>goog.require(&#39;goog.Disposable&#39;);
<a name="line23"></a>goog.require(&#39;goog.array&#39;);
<a name="line24"></a>
<a name="line25"></a>
<a name="line26"></a>
<a name="line27"></a>/**
<a name="line28"></a> * Topic-based publish/subscribe channel.  Maintains a map of topics to
<a name="line29"></a> * subscriptions.  When a message is published to a topic, all functions
<a name="line30"></a> * subscribed to that topic are invoked in the order they were added.
<a name="line31"></a> * Uncaught errors abort publishing.
<a name="line32"></a> *
<a name="line33"></a> * Topics may be identified by any nonempty string, &lt;strong&gt;except&lt;/strong&gt;
<a name="line34"></a> * strings corresponding to native Object properties, e.g. &quot;constructor&quot;,
<a name="line35"></a> * &quot;toString&quot;, &quot;hasOwnProperty&quot;, etc.
<a name="line36"></a> *
<a name="line37"></a> * @constructor
<a name="line38"></a> * @extends {goog.Disposable}
<a name="line39"></a> */
<a name="line40"></a>goog.pubsub.PubSub = function() {
<a name="line41"></a>  goog.Disposable.call(this);
<a name="line42"></a>  this.subscriptions_ = [];
<a name="line43"></a>  this.topics_ = {};
<a name="line44"></a>};
<a name="line45"></a>goog.inherits(goog.pubsub.PubSub, goog.Disposable);
<a name="line46"></a>
<a name="line47"></a>
<a name="line48"></a>/**
<a name="line49"></a> * Sparse array of subscriptions.  Each subscription is represented by a tuple
<a name="line50"></a> * comprising a topic identifier, a function, and an optional context object.
<a name="line51"></a> * Each tuple occupies three consecutive positions in the array, with the topic
<a name="line52"></a> * identifier at index n, the function at index (n + 1), the context object at
<a name="line53"></a> * index (n + 2), the next topic at index (n + 3), etc.  (This representation
<a name="line54"></a> * minimizes the number of object allocations and has been shown to be faster
<a name="line55"></a> * than an array of objects with three key-value pairs or three parallel arrays,
<a name="line56"></a> * especially on IE.)  Once a subscription is removed via {@link #unsubscribe}
<a name="line57"></a> * or {@link #unsubscribeByKey}, the three corresponding array elements are
<a name="line58"></a> * deleted, and never reused.  This means the total number of subscriptions
<a name="line59"></a> * during the lifetime of the pubsub channel is limited by the maximum length
<a name="line60"></a> * of a JavaScript array to (2^32 - 1) / 3 = 1,431,655,765 subscriptions, which
<a name="line61"></a> * should suffice for most applications.
<a name="line62"></a> *
<a name="line63"></a> * @type {!Array}
<a name="line64"></a> * @private
<a name="line65"></a> */
<a name="line66"></a>goog.pubsub.PubSub.prototype.subscriptions_;
<a name="line67"></a>
<a name="line68"></a>
<a name="line69"></a>/**
<a name="line70"></a> * The next available subscription key.  Internally, this is an index into the
<a name="line71"></a> * sparse array of subscriptions.
<a name="line72"></a> *
<a name="line73"></a> * @type {number}
<a name="line74"></a> * @private
<a name="line75"></a> */
<a name="line76"></a>goog.pubsub.PubSub.prototype.key_ = 1;
<a name="line77"></a>
<a name="line78"></a>
<a name="line79"></a>/**
<a name="line80"></a> * Map of topics to arrays of subscription keys.
<a name="line81"></a> *
<a name="line82"></a> * @type {!Object.&lt;!Array.&lt;number&gt;&gt;}
<a name="line83"></a> * @private
<a name="line84"></a> */
<a name="line85"></a>goog.pubsub.PubSub.prototype.topics_;
<a name="line86"></a>
<a name="line87"></a>
<a name="line88"></a>/**
<a name="line89"></a> * Array of subscription keys pending removal once publishing is done.
<a name="line90"></a> *
<a name="line91"></a> * @type {Array.&lt;number&gt;}
<a name="line92"></a> * @private
<a name="line93"></a> */
<a name="line94"></a>goog.pubsub.PubSub.prototype.pendingKeys_;
<a name="line95"></a>
<a name="line96"></a>
<a name="line97"></a>/**
<a name="line98"></a> * Lock to prevent the removal of subscriptions during publishing.  Incremented
<a name="line99"></a> * at the beginning of {@link #publish}, and decremented at the end.
<a name="line100"></a> *
<a name="line101"></a> * @type {number}
<a name="line102"></a> * @private
<a name="line103"></a> */
<a name="line104"></a>goog.pubsub.PubSub.prototype.publishDepth_ = 0;
<a name="line105"></a>
<a name="line106"></a>
<a name="line107"></a>/**
<a name="line108"></a> * Subscribes a function to a topic.  The function is invoked as a method on
<a name="line109"></a> * the given {@code opt_context} object, or in the global scope if no context
<a name="line110"></a> * is specified.  Subscribing the same function to the same topic multiple
<a name="line111"></a> * times will result in multiple function invocations while publishing.
<a name="line112"></a> * Returns a subscription key that can be used to unsubscribe the function from
<a name="line113"></a> * the topic via {@link #unsubscribeByKey}.
<a name="line114"></a> *
<a name="line115"></a> * @param {string} topic Topic to subscribe to.
<a name="line116"></a> * @param {Function} fn Function to be invoked when a message is published to
<a name="line117"></a> *     the given topic.
<a name="line118"></a> * @param {Object=} opt_context Object in whose context the function is to be
<a name="line119"></a> *     called (the global scope if none).
<a name="line120"></a> * @return {number} Subscription key.
<a name="line121"></a> */
<a name="line122"></a>goog.pubsub.PubSub.prototype.subscribe = function(topic, fn, opt_context) {
<a name="line123"></a>  var keys = this.topics_[topic];
<a name="line124"></a>  if (!keys) {
<a name="line125"></a>    // First subscription to this topic; initialize subscription key array.
<a name="line126"></a>    keys = this.topics_[topic] = [];
<a name="line127"></a>  }
<a name="line128"></a>
<a name="line129"></a>  // Push the tuple representing the subscription onto the subscription array.
<a name="line130"></a>  var key = this.key_;
<a name="line131"></a>  this.subscriptions_[key] = topic;
<a name="line132"></a>  this.subscriptions_[key + 1] = fn;
<a name="line133"></a>  this.subscriptions_[key + 2] = opt_context;
<a name="line134"></a>  this.key_ = key + 3;
<a name="line135"></a>
<a name="line136"></a>  // Push the subscription key onto the list of subscriptions for the topic.
<a name="line137"></a>  keys.push(key);
<a name="line138"></a>
<a name="line139"></a>  // Return the subscription key.
<a name="line140"></a>  return key;
<a name="line141"></a>};
<a name="line142"></a>
<a name="line143"></a>
<a name="line144"></a>/**
<a name="line145"></a> * Subscribes a single-use function to a topic.  The function is invoked as a
<a name="line146"></a> * method on the given {@code opt_context} object, or in the global scope if
<a name="line147"></a> * no context is specified, and is then unsubscribed.  Returns a subscription
<a name="line148"></a> * key that can be used to unsubscribe the function from the topic via
<a name="line149"></a> * {@link #unsubscribeByKey}.
<a name="line150"></a> *
<a name="line151"></a> * @param {string} topic Topic to subscribe to.
<a name="line152"></a> * @param {Function} fn Function to be invoked once and then unsubscribed when
<a name="line153"></a> *     a message is published to the given topic.
<a name="line154"></a> * @param {Object=} opt_context Object in whose context the function is to be
<a name="line155"></a> *     called (the global scope if none).
<a name="line156"></a> * @return {number} Subscription key.
<a name="line157"></a> */
<a name="line158"></a>goog.pubsub.PubSub.prototype.subscribeOnce = function(topic, fn, opt_context) {
<a name="line159"></a>  // Behold the power of lexical closures!
<a name="line160"></a>  var key = this.subscribe(topic, function(var_args) {
<a name="line161"></a>    fn.apply(opt_context, arguments);
<a name="line162"></a>    this.unsubscribeByKey(key);
<a name="line163"></a>  }, this);
<a name="line164"></a>  return key;
<a name="line165"></a>};
<a name="line166"></a>
<a name="line167"></a>
<a name="line168"></a>/**
<a name="line169"></a> * Unsubscribes a function from a topic.  Only deletes the first match found.
<a name="line170"></a> * Returns a Boolean indicating whether a subscription was removed.
<a name="line171"></a> *
<a name="line172"></a> * @param {string} topic Topic to unsubscribe from.
<a name="line173"></a> * @param {Function} fn Function to unsubscribe.
<a name="line174"></a> * @param {Object=} opt_context Object in whose context the function was to be
<a name="line175"></a> *     called (the global scope if none).
<a name="line176"></a> * @return {boolean} Whether a matching subscription was removed.
<a name="line177"></a> */
<a name="line178"></a>goog.pubsub.PubSub.prototype.unsubscribe = function(topic, fn, opt_context) {
<a name="line179"></a>  var keys = this.topics_[topic];
<a name="line180"></a>  if (keys) {
<a name="line181"></a>    // Find the subscription key for the given combination of topic, function,
<a name="line182"></a>    // and context object.
<a name="line183"></a>    var subscriptions = this.subscriptions_;
<a name="line184"></a>    var key = goog.array.find(keys, function(k) {
<a name="line185"></a>      return subscriptions[k + 1] == fn &amp;&amp; subscriptions[k + 2] == opt_context;
<a name="line186"></a>    });
<a name="line187"></a>    // Zero is not a valid key.
<a name="line188"></a>    if (key) {
<a name="line189"></a>      return this.unsubscribeByKey(/** @type {number} */ (key));
<a name="line190"></a>    }
<a name="line191"></a>  }
<a name="line192"></a>
<a name="line193"></a>  return false;
<a name="line194"></a>};
<a name="line195"></a>
<a name="line196"></a>
<a name="line197"></a>/**
<a name="line198"></a> * Removes a subscription based on the key returned by {@link #subscribe}.
<a name="line199"></a> * No-op if no matching subscription is found.  Returns a Boolean indicating
<a name="line200"></a> * whether a subscription was removed.
<a name="line201"></a> *
<a name="line202"></a> * @param {number} key Subscription key.
<a name="line203"></a> * @return {boolean} Whether a matching subscription was removed.
<a name="line204"></a> */
<a name="line205"></a>goog.pubsub.PubSub.prototype.unsubscribeByKey = function(key) {
<a name="line206"></a>  if (this.publishDepth_ != 0) {
<a name="line207"></a>    // Defer removal until after publishing is complete.
<a name="line208"></a>    if (!this.pendingKeys_) {
<a name="line209"></a>      this.pendingKeys_ = [];
<a name="line210"></a>    }
<a name="line211"></a>    this.pendingKeys_.push(key);
<a name="line212"></a>    return false;
<a name="line213"></a>  }
<a name="line214"></a>
<a name="line215"></a>  var topic = this.subscriptions_[key];
<a name="line216"></a>  if (topic) {
<a name="line217"></a>    // Subscription tuple found.
<a name="line218"></a>    var keys = this.topics_[topic];
<a name="line219"></a>    if (keys) {
<a name="line220"></a>      goog.array.remove(keys, key);
<a name="line221"></a>    }
<a name="line222"></a>    delete this.subscriptions_[key];
<a name="line223"></a>    delete this.subscriptions_[key + 1];
<a name="line224"></a>    delete this.subscriptions_[key + 2];
<a name="line225"></a>  }
<a name="line226"></a>
<a name="line227"></a>  return !!topic;
<a name="line228"></a>};
<a name="line229"></a>
<a name="line230"></a>
<a name="line231"></a>/**
<a name="line232"></a> * Publishes a message to a topic.  Calls functions subscribed to the topic in
<a name="line233"></a> * the order in which they were added, passing all arguments along.  If any of
<a name="line234"></a> * the functions throws an uncaught error, publishing is aborted.
<a name="line235"></a> *
<a name="line236"></a> * @param {string} topic Topic to publish to.
<a name="line237"></a> * @param {...*} var_args Arguments that are applied to each subscription
<a name="line238"></a> *     function.
<a name="line239"></a> * @return {boolean} Whether any subscriptions were called.
<a name="line240"></a> */
<a name="line241"></a>goog.pubsub.PubSub.prototype.publish = function(topic, var_args) {
<a name="line242"></a>  var keys = this.topics_[topic];
<a name="line243"></a>  if (keys) {
<a name="line244"></a>    // We must lock subscriptions and remove them at the end, so we don&#39;t
<a name="line245"></a>    // adversely affect the performance of the common case by cloning the key
<a name="line246"></a>    // array.
<a name="line247"></a>    this.publishDepth_++;
<a name="line248"></a>
<a name="line249"></a>    // For each key in the list of subscription keys for the topic, apply the
<a name="line250"></a>    // function to the arguments in the appropriate context.  The length of the
<a name="line251"></a>    // array mush be fixed during the iteration, since subscribers may add new
<a name="line252"></a>    // subscribers during publishing.
<a name="line253"></a>    var args = goog.array.slice(arguments, 1);
<a name="line254"></a>    for (var i = 0, len = keys.length; i &lt; len; i++) {
<a name="line255"></a>      var key = keys[i];
<a name="line256"></a>      this.subscriptions_[key + 1].apply(this.subscriptions_[key + 2], args);
<a name="line257"></a>    }
<a name="line258"></a>
<a name="line259"></a>    // Unlock subscriptions.
<a name="line260"></a>    this.publishDepth_--;
<a name="line261"></a>
<a name="line262"></a>    if (this.pendingKeys_ &amp;&amp; this.publishDepth_ == 0) {
<a name="line263"></a>      var pendingKey;
<a name="line264"></a>      while ((pendingKey = this.pendingKeys_.pop())) {
<a name="line265"></a>        this.unsubscribeByKey(pendingKey);
<a name="line266"></a>      }
<a name="line267"></a>    }
<a name="line268"></a>
<a name="line269"></a>    // At least one subscriber was called.
<a name="line270"></a>    return i != 0;
<a name="line271"></a>  }
<a name="line272"></a>
<a name="line273"></a>  // No subscribers were found.
<a name="line274"></a>  return false;
<a name="line275"></a>};
<a name="line276"></a>
<a name="line277"></a>
<a name="line278"></a>/**
<a name="line279"></a> * Clears the subscription list for a topic, or all topics if unspecified.
<a name="line280"></a> * @param {string=} opt_topic Topic to clear (all topics if unspecified).
<a name="line281"></a> */
<a name="line282"></a>goog.pubsub.PubSub.prototype.clear = function(opt_topic) {
<a name="line283"></a>  if (opt_topic) {
<a name="line284"></a>    var keys = this.topics_[opt_topic];
<a name="line285"></a>    if (keys) {
<a name="line286"></a>      goog.array.forEach(keys, this.unsubscribeByKey, this);
<a name="line287"></a>      delete this.topics_[opt_topic];
<a name="line288"></a>    }
<a name="line289"></a>  } else {
<a name="line290"></a>    this.subscriptions_.length = 0;
<a name="line291"></a>    this.topics_ = {};
<a name="line292"></a>    // We don&#39;t reset key_ on purpose, because we want subscription keys to be
<a name="line293"></a>    // unique throughout the lifetime of the application.  Reusing subscription
<a name="line294"></a>    // keys could lead to subtle errors in client code.
<a name="line295"></a>  }
<a name="line296"></a>};
<a name="line297"></a>
<a name="line298"></a>
<a name="line299"></a>/**
<a name="line300"></a> * Returns the number of subscriptions to the given topic (or all topics if
<a name="line301"></a> * unspecified).
<a name="line302"></a> * @param {string=} opt_topic The topic (all topics if unspecified).
<a name="line303"></a> * @return {number} Number of subscriptions to the topic.
<a name="line304"></a> */
<a name="line305"></a>goog.pubsub.PubSub.prototype.getCount = function(opt_topic) {
<a name="line306"></a>  if (opt_topic) {
<a name="line307"></a>    var keys = this.topics_[opt_topic];
<a name="line308"></a>    return keys ? keys.length : 0;
<a name="line309"></a>  }
<a name="line310"></a>
<a name="line311"></a>  var count = 0;
<a name="line312"></a>  for (var topic in this.topics_) {
<a name="line313"></a>    count += this.getCount(topic);
<a name="line314"></a>  }
<a name="line315"></a>
<a name="line316"></a>  return count;
<a name="line317"></a>};
<a name="line318"></a>
<a name="line319"></a>
<a name="line320"></a>/** @override */
<a name="line321"></a>goog.pubsub.PubSub.prototype.disposeInternal = function() {
<a name="line322"></a>  goog.pubsub.PubSub.superClass_.disposeInternal.call(this);
<a name="line323"></a>  delete this.subscriptions_;
<a name="line324"></a>  delete this.topics_;
<a name="line325"></a>  delete this.pendingKeys_;
<a name="line326"></a>};
</pre>


</body>
</html>
